
// 题库数据将从questions.js文件加载
let allQuestions = window.allQuestions || [];
let questions = []; // 当前考试题目（从allQuestions中随机抽取50道）
let currentQuestionIndex = 0; // 当前题目索引
let userAnswers = []; // 用户答案
let examTime = 60 * 60; // 考试时间（秒）
let timerInterval = null; // 计时器
let wrongQuestions = []; // 错题记录
let trainingQuestions = []; // 训练题目
let isExamStarted = false; // 考试是否已开始

// DOM元素
const sections = {
    exam: document.getElementById('examSection'),
    wrongQuestions: document.getElementById('wrongQuestionsSection'),
    training: document.getElementById('trainingSection')
};

const navButtons = {
    exam: document.getElementById('examBtn'),
    wrongQuestions: document.getElementById('wrongQuestionsBtn'),
    training: document.getElementById('trainingBtn')
};

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initializeNavigation();
    initializeExam();
    initializeTraining();
    initializeQuestions();
    loadFromLocalStorage();
});

// 初始化导航
function initializeNavigation() {
    Object.keys(navButtons).forEach(key => {
        navButtons[key].addEventListener('click', () => switchSection(key));
    });
}

// 切换界面
function switchSection(sectionName) {
    // 隐藏所有界面
    Object.values(sections).forEach(section => {
        section.classList.remove('active');
    });
    
    // 移除所有按钮的激活状态
    Object.values(navButtons).forEach(button => {
        button.classList.remove('active');
    });
    
    // 显示目标界面并激活对应按钮
    sections[sectionName].classList.add('active');
    navButtons[sectionName].classList.add('active');
    
    // 特殊处理
    if (sectionName === 'wrongQuestions') {
        displayWrongQuestions();
    }
}

// 初始化考试功能
function initializeExam() {
    document.getElementById('startExamBtn').addEventListener('click', startRandomExam);
    document.getElementById('prevBtn').addEventListener('click', showPreviousQuestion);
    document.getElementById('nextBtn').addEventListener('click', showNextQuestion);
    document.getElementById('submitBtn').addEventListener('click', submitExam);
}

// 初始化题库
function initializeQuestions() {
    userAnswers = new Array(questions.length).fill(null);
    currentQuestionIndex = 0;
    updateTotalQuestions();
    showCurrentQuestion();
    console.log(`成功初始化 ${questions.length} 道题目`);
}

// 初始化训练功能
function initializeTraining() {
    document.getElementById('startTraining').addEventListener('click', startTraining);
    document.getElementById('resetTraining').addEventListener('click', resetTraining);
}

// 从本地存储加载数据
function loadFromLocalStorage() {
    const savedQuestions = localStorage.getItem('questions');
    const savedWrongQuestions = localStorage.getItem('wrongQuestions');
    
    if (savedQuestions) {
        questions = JSON.parse(savedQuestions);
        updateTotalQuestions();
    }
    
    if (savedWrongQuestions) {
        wrongQuestions = JSON.parse(savedWrongQuestions);
    }
}

// 保存数据到本地存储
function saveToLocalStorage() {
    localStorage.setItem('questions', JSON.stringify(questions));
    localStorage.setItem('wrongQuestions', JSON.stringify(wrongQuestions));
}




// 更新总题数显示
function updateTotalQuestions() {
    document.getElementById('totalQuestions').textContent = questions.length;
}

// 显示当前题目
function showCurrentQuestion() {
    if (questions.length === 0) {
        document.getElementById('questionContent').innerHTML = '<p>请先导入题库开始考试</p>';
        document.getElementById('optionsContainer').innerHTML = '';
        return;
    }
    
    const question = questions[currentQuestionIndex];
    document.getElementById('questionContent').innerHTML = `
        <p><strong>${question.id}.（${question.type}）</strong> ${question.question}</p>
    `;
    
    document.getElementById('currentQuestionNum').textContent = currentQuestionIndex + 1;
    
    // 生成选项
    const optionsContainer = document.getElementById('optionsContainer');
    optionsContainer.innerHTML = '';
    
    question.options.forEach(option => {
        const optionElement = document.createElement('div');
        optionElement.className = 'option-item';
        
        const inputType = question.type === '单选题' ? 'radio' : 'checkbox';
        const inputName = question.type === '单选题' ? `question-${currentQuestionIndex}` : `question-${currentQuestionIndex}-${option.key}`;
        
        optionElement.innerHTML = `
            <input type="${inputType}" name="${inputName}" value="${option.key}" 
                   ${isOptionSelected(option.key) ? 'checked' : ''}>
            <span class="option-label">${option.key}. ${option.text}</span>
        `;
        
        optionElement.addEventListener('click', (e) => {
            if (e.target.type !== inputType) {
                const input = optionElement.querySelector('input');
                if (question.type === '单选题') {
                    // 单选题：取消其他选项的选择
                    document.querySelectorAll(`input[name="${inputName}"]`).forEach(inp => {
                        inp.checked = false;
                        inp.parentElement.classList.remove('selected');
                    });
                }
                input.checked = !input.checked;
            }
            
            // 更新选中状态
            if (inputType === 'checkbox') {
                optionElement.classList.toggle('selected', optionElement.querySelector('input').checked);
            } else {
                document.querySelectorAll(`.option-item`).forEach(item => {
                    item.classList.remove('selected');
                });
                if (optionElement.querySelector('input').checked) {
                    optionElement.classList.add('selected');
                }
            }
            
            saveUserAnswer();
        });
        
        optionsContainer.appendChild(optionElement);
    });
    
    // 更新导航按钮状态
    updateNavigationButtons();
}

// 检查选项是否被选中
function isOptionSelected(optionKey) {
    const currentAnswer = userAnswers[currentQuestionIndex];
    if (!currentAnswer) return false;
    
    if (typeof currentAnswer === 'string') {
        return currentAnswer === optionKey;
    } else if (Array.isArray(currentAnswer)) {
        return currentAnswer.includes(optionKey);
    }
    return false;
}

// 保存用户答案
function saveUserAnswer() {
    const question = questions[currentQuestionIndex];
    let selectedOptions = [];
    
    if (question.type === '单选题') {
        const selected = document.querySelector(`input[name="question-${currentQuestionIndex}"]:checked`);
        selectedOptions = selected ? selected.value : null;
    } else {
        // 多选题
        const selected = document.querySelectorAll(`input[name^="question-${currentQuestionIndex}-"]:checked`);
        selectedOptions = Array.from(selected).map(input => input.value);
    }
    
    userAnswers[currentQuestionIndex] = selectedOptions;
}

// 更新导航按钮状态
function updateNavigationButtons() {
    document.getElementById('prevBtn').disabled = currentQuestionIndex === 0;
    document.getElementById('nextBtn').disabled = currentQuestionIndex === questions.length - 1;
}

// 显示上一题
function showPreviousQuestion() {
    if (currentQuestionIndex > 0) {
        currentQuestionIndex--;
        showCurrentQuestion();
    }
}

// 显示下一题
function showNextQuestion() {
    if (currentQuestionIndex < questions.length - 1) {
        currentQuestionIndex++;
        showCurrentQuestion();
    }
}

// 开始考试计时器
function startExamTimer() {
    clearInterval(timerInterval);
    examTime = 60 * 60; // 重置为60分钟
    
    timerInterval = setInterval(() => {
        examTime--;
        
        if (examTime <= 0) {
            clearInterval(timerInterval);
            submitExam();
            return;
        }
        
        const minutes = Math.floor(examTime / 60);
        const seconds = examTime % 60;
        document.getElementById('timeLeft').textContent = 
            `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }, 1000);
}

// 提交考试
function submitExam() {
    clearInterval(timerInterval);
    
    // 计算分数和错题
    let score = 0;
    const newWrongQuestions = [];
    
    questions.forEach((question, index) => {
        const userAnswer = userAnswers[index];
        const correctAnswer = question.answer.split(' ');
        
        let isCorrect = false;
        
        if (question.type === '单选题') {
            isCorrect = userAnswer === correctAnswer[0];
        } else {
            // 多选题：答案顺序无关，但必须完全匹配
            isCorrect = Array.isArray(userAnswer) && 
                       userAnswer.length === correctAnswer.length &&
                       userAnswer.every(ans => correctAnswer.includes(ans)) &&
                       correctAnswer.every(ans => userAnswer.includes(ans));
        }
        
        if (isCorrect) {
            score++;
        } else {
            newWrongQuestions.push({
                ...question,
                userAnswer: userAnswer,
                index: index
            });
        }
    });
    
    // 更新错题库
    wrongQuestions = [...wrongQuestions, ...newWrongQuestions];
    saveToLocalStorage();
    
    // 显示考试结果
    const percentage = ((score / questions.length) * 100).toFixed(1);
    alert(`考试结束！\n得分: ${score}/${questions.length} (${percentage}%)\n错题数: ${newWrongQuestions.length}`);
    
    // 重置考试状态
    currentQuestionIndex = 0;
    userAnswers = new Array(questions.length).fill(null);
    showCurrentQuestion();
}

// 显示错题库
function displayWrongQuestions() {
    const wrongQuestionsList = document.getElementById('wrongQuestionsList');
    
    if (wrongQuestions.length === 0) {
        wrongQuestionsList.innerHTML = '<p>暂无错题记录</p>';
        return;
    }
    
    wrongQuestionsList.innerHTML = wrongQuestions.map((question, index) => `
        <div class="wrong-question-item">
            <h4>${question.id}.（${question.type}） ${question.question}</h4>
            <div class="wrong-question-options">
                ${question.options.map(option => {
                    const isCorrect = question.answer.includes(option.key);
                    const isUserSelected = Array.isArray(question.userAnswer) ? 
                        question.userAnswer.includes(option.key) : 
                        question.userAnswer === option.key;
                    
                    let className = 'wrong-option';
                    if (isCorrect) className += ' correct';
                    if (isUserSelected && !isCorrect) className += ' incorrect';
                    
                    return `<div class="${className}">${option.key}. ${option.text}</div>`;
                }).join('')}
            </div>
            <div class="wrong-answer-info">
                <strong>正确答案:</strong> ${question.answer} | 
                <strong>你的答案:</strong> ${Array.isArray(question.userAnswer) ? question.userAnswer.join(' ') : question.userAnswer || '未作答'}
            </div>
        </div>
    `).join('');
}

// 开始错题强化训练
function startTraining() {
    if (wrongQuestions.length === 0) {
        alert('暂无错题可训练');
        return;
    }
    
    trainingQuestions = [...wrongQuestions];
    currentQuestionIndex = 0;
    userAnswers = new Array(trainingQuestions.length).fill(null);
    
    displayTrainingQuestion();
}

// 显示训练题目
function displayTrainingQuestion() {
    const trainingContainer = document.getElementById('trainingContainer');
    
    if (trainingQuestions.length === 0) {
        trainingContainer.innerHTML = '<p>训练完成！</p>';
        return;
    }
    
    const question = trainingQuestions[currentQuestionIndex];
    trainingContainer.innerHTML = `
        <div class="question-content">
            <p><strong>${question.id}.（${question.type}）</strong> ${question.question}</p>
        </div>
        <div class="options-container">
            ${question.options.map(option => `
                <div class="option-item">
                    <input type="${question.type === '单选题' ? 'radio' : 'checkbox'}" 
                           name="training-question" value="${option.key}">
                    <span class="option-label">${option.key}. ${option.text}</span>
                </div>
            `).join('')}
        </div>
        <div class="navigation-buttons">
            <button id="trainingPrevBtn" class="nav-button">上一题</button>
            <button id="trainingNextBtn" class="nav-button">下一题</button>
            <button id="trainingSubmitBtn" class="submit-button">提交答案</button>
        </div>
        <div id="trainingResult"></div>
    `;
    
    // 添加训练事件监听
    document.getElementById('trainingPrevBtn').addEventListener('click', showPreviousTrainingQuestion);
    document.getElementById('trainingNextBtn').addEventListener('click', showNextTrainingQuestion);
    document.getElementById('trainingSubmitBtn').addEventListener('click', submitTrainingAnswer);
    
    // 添加选项点击事件
    document.querySelectorAll('#trainingContainer .option-item').forEach(item => {
        item.addEventListener('click', function(e) {
            if (e.target.type !== 'checkbox' && e.target.type !== 'radio') {
                const input = this.querySelector('input');
                if (question.type === '单选题') {
                    document.querySelectorAll('#trainingContainer input[type="radio"]').forEach(inp => {
                        inp.checked = false;
                        inp.parentElement.classList.remove('selected');
                    });
                }
                input.checked = !input.checked;
            }
            
            if (question.type === 'checkbox') {
                this.classList.toggle('selected', this.querySelector('input').checked);
            } else {
                document.querySelectorAll('#trainingContainer .option-item').forEach(opt => {
                    opt.classList.remove('selected');
                });
                if (this.querySelector('input').checked) {
                    this.classList.add('selected');
                }
            }
        });
    });
}

// 显示上一道训练题
function showPreviousTrainingQuestion() {
    if (currentQuestionIndex > 0) {
        currentQuestionIndex--;
        displayTrainingQuestion();
    }
}

// 显示下一道训练题
function showNextTrainingQuestion() {
    if (currentQuestionIndex < trainingQuestions.length - 1) {
        currentQuestionIndex++;
        displayTrainingQuestion();
    }
}

// 提交训练答案
function submitTrainingAnswer() {
    const question = trainingQuestions[currentQuestionIndex];
    const trainingResult = document.getElementById('trainingResult');
    
    // 获取用户答案
    let userAnswer = [];
    if (question.type === '单选题') {
        const selected = document.querySelector('#trainingContainer input[type="radio"]:checked');
        userAnswer = selected ? selected.value : null;
    } else {
        const selected = document.querySelectorAll('#trainingContainer input[type="checkbox"]:checked');
        userAnswer = Array.from(selected).map(input => input.value);
    }
    
    if (!userAnswer || (Array.isArray(userAnswer) && userAnswer.length === 0)) {
        trainingResult.innerHTML = '<p style="color: #e53e3e;">请先选择答案</p>';
        return;
    }
    
    // 检查答案
    const correctAnswer = question.answer.split(' ');
    let isCorrect = false;
    
    if (question.type === '单选题') {
        isCorrect = userAnswer === correctAnswer[0];
    } else {
        isCorrect = Array.isArray(userAnswer) && 
                   userAnswer.length === correctAnswer.length &&
                   userAnswer.every(ans => correctAnswer.includes(ans)) &&
                   correctAnswer.every(ans => userAnswer.includes(ans));
    }
    
    // 显示结果
    if (isCorrect) {
        trainingResult.innerHTML = `
            <p style="color: #38a169; font-weight: bold;">✓ 回答正确！</p>
            <p>正确答案: ${question.answer}</p>
        `;
        
        // 从错题库中移除已答对的题目
        const wrongQuestionIndex = wrongQuestions.findIndex(wq => wq.id === question.id);
        if (wrongQuestionIndex !== -1) {
            wrongQuestions.splice(wrongQuestionIndex, 1);
            saveToLocalStorage();
        }
        
        // 从训练题目中移除已答对的题目
        trainingQuestions.splice(currentQuestionIndex, 1);
        
        if (trainingQuestions.length === 0) {
            setTimeout(() => {
                trainingContainer.innerHTML = '<p style="color: #38a169; font-weight: bold;">🎉 训练完成！所有错题都已掌握！</p>';
            }, 1500);
        } else {
            if (currentQuestionIndex >= trainingQuestions.length) {
                currentQuestionIndex = trainingQuestions.length - 1;
            }
            setTimeout(displayTrainingQuestion, 1500);
        }
    } else {
        trainingResult.innerHTML = `
            <p style="color: #e53e3e; font-weight: bold;">✗ 回答错误</p>
            <p>你的答案: ${Array.isArray(userAnswer) ? userAnswer.join(' ') : userAnswer}</p>
            <p>正确答案: ${question.answer}</p>
        `;
    }
}

// 重置训练
function resetTraining() {
    trainingQuestions = [];
    currentQuestionIndex = 0;
    userAnswers = [];
    document.getElementById('trainingContainer').innerHTML = '<p>点击"开始训练"开始错题强化训练</p>';
}

// 开始随机考试（从题库中随机抽取50道题目）
function startRandomExam() {
    if (allQuestions.length === 0) {
        alert('题库为空，请先导入题库');
        return;
    }
    
    // 随机抽取50道题目
    const shuffled = [...allQuestions].sort(() => 0.5 - Math.random());
    questions = shuffled.slice(0, 50);
    
    // 重置考试状态
    currentQuestionIndex = 0;
    userAnswers = new Array(questions.length).fill(null);
    isExamStarted = true;
    
    // 更新界面显示
    updateTotalQuestions();
    showCurrentQuestion();
    startExamTimer();
    
    // 隐藏开始考试按钮，显示考试界面
    document.getElementById('startExamBtn').style.display = 'none';
    document.getElementById('examContent').style.display = 'block';
    
    alert(`考试开始！本次考试共 ${questions.length} 道题目，时间60分钟。`);
}

// 开始考试计时器
function startExamTimer() {
    clearInterval(timerInterval);
    examTime = 60 * 60; // 重置为60分钟
    
    timerInterval = setInterval(() => {
        examTime--;
        
        if (examTime <= 0) {
            clearInterval(timerInterval);
            submitExam();
            return;
        }
        
        const minutes = Math.floor(examTime / 60);
        const seconds = examTime % 60;
        document.getElementById('timeLeft').textContent = 
            `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }, 1000);
}
